<template>
    <div class="chart-data-matching-show">
        <a-timeline>
            <!-- 数据映射 -->
            <a-timeline-item v-if="isCharts && dimensionsAndSource">
                <div class="data-mapping">
                    <div class="dot-title">
                        {{ TimelineTitleEnum.MAPPING }}
                    </div>
                    <table class="matching-table">
                        <thead>
                            <tr>
                                <th v-for="i in tableTitle" :key="i">{{ i }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="i in dimensionsAndSource" :key="i">
                                <td>
                                    {{ i.field }}
                                </td>
                                <td>
                                    {{ i.mapping }}
                                </td>
                                <td>
                                    <a-space v-if="i.result == 0">
                                        无
                                    </a-space>
                                    <a-space v-else>
                                        匹配{{ i.result === 1 ? '成功' : '失败' }}
                                    </a-space>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </a-timeline-item>
            <!-- 数据过滤 -->
            <a-timeline-item v-if="filterShow">
                <div class="data-filter">
                    <div class="dot-title">
                        {{ TimelineTitleEnum.FILTER }}
                    </div>
                    <div class="filter">
                        <span class="tip">
                            过滤器默认处理接口返回值的「data」字段
                        </span>
                        <chart-data-editor/>
                    </div>
                </div>
            </a-timeline-item>
            <!-- 数据内容 -->
            <a-timeline-item color="green">
                <div class="data-content">
                    <div class="dot-title">
                        {{ TimelineTitleEnum.CONTENT }}
                    </div>
                    <div class="data">
                        <a-space class="mb-2">
                            <a-button @click="openOnlineEditHandle" :disabled="noData" :icon="h(EditOutlined)">编辑</a-button>
                            <a-upload
                                name="file"
                                v-model:file-list="fileList"
                                :customRequest="customRequest"
                                :showUploadList="false"
                            >
                                <a-button>
                                <FileAddOutlined></FileAddOutlined>
                                    导入(json)
                                </a-button>
                            </a-upload>
                            <a-button @click="download" :disabled="noData" :icon="h(CloudDownloadOutlined)">下载</a-button>
                        </a-space>
                        <a-card style="width: 100%;overflow: hidden;">
                            <highlightjs language="json" :code="JSON.stringify(source)"></highlightjs>
                        </a-card>
                    </div>
                </div>
            </a-timeline-item>
        </a-timeline>
        <custom-drawer v-model="visible" :width="740">
            <div class="code-view">
                <header>
                    组件数据在线编辑--{{ targetData.chartConfig.title }}
                </header>
                <editor ref="editorRef" :source="source" editor-type="json"/>
                <a-row :gutter="10">
                    <a-col :span="12">
                        <a-button style="width: 100%;" @click="handleSubmitEdiotrData" type="primary">确定</a-button>
                    </a-col>
                    <a-col :span="12">
                        <a-button style="width: 100%;" @click="visible = false">取消</a-button>
                    </a-col>
                </a-row>
            </div>
        </custom-drawer>
    </div>
</template>

<script setup lang="ts">
import { computed, h, ref, useTemplateRef, watch } from 'vue';
import { useTargetData } from '../../../../hooks/useTargetData';
import { ChartFrameEnum } from '@/views/dataview/packages/enum';
import { DataResultEnum, TimelineTitleEnum } from '../../data';
import { result } from 'lodash';
import { RequestDataTypeEnum } from '@/const';
import { CloudDownloadOutlined, EditOutlined, FileAddOutlined } from '@ant-design/icons-vue';
import hljsVuePlugin  from "@highlightjs/vue-plugin";
import 'highlight.js/lib/common';
import customDrawer from '@/components/custom-drawer/index.vue'
import editor from '@/components/editor/index.vue'
import { blobToFile, downloadFile, showMsg } from '@/utils';
import chartDataEditor from '../ChartDataEditor/index.vue'

const highlightjs = hljsVuePlugin.component


withDefaults(defineProps<{
    show:boolean,
    ajax:boolean
}>(),{})

const editorRef = useTemplateRef("editorRef")
const {targetData} = useTargetData()
const tableTitle = ['字段', '映射', '状态']
const dimensionsAndSource = ref()
const dimensions = ref()
const noData = ref(false)
const source = ref()
const visible = ref(false)
const fileList = ref([])

// dataset类型图表数据
const isCharts = computed(()=>{
    return targetData.value.chartConfig.chartFrame === ChartFrameEnum.ECHARTS
})

const filterShow = computed(()=>{
    return targetData.value.request.requestDataType !== RequestDataTypeEnum.STATIC
})

const matchingHandle = (mapping:string)=>{
    let res = DataResultEnum.SUCCESS
    for (let i = 0; i < source.value.length; i++) {
        if(source.value[i][mapping] == undefined){
            res = DataResultEnum.FAILURE
            return res
        }
    }
    return res
}

// 处理映射
const dimensionsAndSourceHandle = ()=>{
    return dimensions.value.map((item:any,index:number)=>{
        return index == 0?
            {
                field:'通用标识',
                mapping:item,
                result:DataResultEnum.NULL
            }
            :
            {
                field: `数据项-${index}`,
                mapping: item,
                result:matchingHandle(item)
            }
    })
}

watch(
    ()=>targetData.value.option.dataset,
    (newData:{source:any,dimensions:any} | null)=>{
        noData.value = false
        if(newData && targetData.value.chartConfig.chartFrame === ChartFrameEnum.ECHARTS){
            // 设置dataset数据格式
            source.value = newData 
            if(isCharts.value){
                dimensions.value = newData.dimensions
                dimensionsAndSource.value = dimensionsAndSourceHandle()
            }
        }
    },
    {
        immediate:true
    }
)


const openOnlineEditHandle = ()=>{
    visible.value = true
}

const handleSubmitEdiotrData = ()=>{
    const value = editorRef.value?.getEditorValue()
    if(value != null){
        targetData.value.option.dataset = value
        visible.value = false
    }
}

const download = ()=>{
    const val = JSON.stringify(targetData.value.option.dataset,null,2)
    const blob = new Blob([val],{type:'application/json'})
    let fileName = "数据"
    downloadFile(blobToFile(blob,fileName),fileName,"json")
}

const customRequest = ({file}:{file:File})=>{
    const allowSuffix = ['json']
    const filename = file.name
    const suffix = filename.split('.').pop() as string
    if(!allowSuffix.includes(suffix)){
        showMsg("上传的文件格式不支持",'warning')
        return
    }
    const reader = new FileReader()
    reader.onload = (e)=>{
        const value = e.target?.result
        targetData.value.option.dataset = JSON.parse(value as string)
    }
    reader.readAsText(file)
}
</script>

<style lang='scss' scoped>
.dot-title{
    margin-bottom: 15px;
}
.matching-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px #f0f1f2;
    overflow: hidden;
    th, td {
        padding: 12px 16px;
        text-align: left;
    }
    thead {
        background: #f5f7fa;
        th {
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #e6e6e6;
        }
    }
    tbody {
        tr {
            transition: background 0.2s;
            &:nth-child(odd) {
                background: #fafbfc;
            }
            &:nth-child(even) {
                background: #f5f7fa;
            }
            &.row-success {
                td:last-child {
                    background: #e6fffb;
                }
            }
            &.row-fail {
                td:last-child {
                    background: #fff1f0;
                }
            }
        }
        td {
            border-bottom: 1px solid #f0f0f0;
        }
        .status-success {
            color: #52c41a;
            font-weight: bold;
        }
        .status-fail {
            color: #ff4d4f;
            font-weight: bold;
        }
        .status-null {
            color: #aaa;
        }
    }
}

:deep(.hljs){
    white-space: normal !important;
}

.code-view{
    header{
        font-size: 24px;
    }
}
.data-filter{
    .filter{
        .tip{
            color:#aaa;
            font-size: 15px;
        }
    }
}
</style>